<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request.js'
import {
	Plus,
	Minus, Delete, Download, ZoomIn
} from '@element-plus/icons-vue'

let tableData = ref([])
onMounted(() => {
	getEmps()

})
const getEmps = (page = 1, pageSize = 5, name = '', gender = '', entryDateStart = '', entryDateEnd = '') => {
	request.get(`/api/emps?pageNo=${page}&pageSize=${pageSize}&name=${name}&gender=${gender}&begin=${entryDateStart}&end=${entryDateEnd}`).then(res => {
		tableData.value = res.data.rows
		pageTotal.value = res.data.total
	})
}
const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}

let editOrAdd = ref('')
const handleEdit = (index, row) => {
	request.get('/api/depts').then(res => {
		deptList.value = res.data
	})
	dialogFormVisible.value = true
	editOrAdd.value = "edit"
	let { id, username, name, gender, image, deptId, job } = row
	form.value.id = id
	form.value.username = username
	form.value.name = name
	form.value.gender = gender
	// ==1?'男':'女'
	form.value.image = image
	form.value.deptId = deptId
	form.value.job = job
	// ==1?'班主任':job==2?'讲师':job==3?'学工主管':job==4?'教研主管':job==5?'咨询师':'null'
	console.log(index, row)
}
const handleDelete = (index, row) => {
	console.log(index, row)
	request.delete('/api/emps/' + row.id).then(res => {
		if (res.code === 0) {
			ElMessage({
				message: res.msg,
				type: 'success',
			})
			getEmps(currentPage4.value, pageSize4.value, searchForm.value.name, searchForm.value.gender, searchForm.value.entryDateStart, searchForm.value.entryDateEnd)
		}
	})

}
const dialogFormVisible = ref(false)
const form = ref({
	id: '',
	username: '',
	name: '',
	gender: '',
	image: '',
	deptId: '',
	job: ''

})
let deptList = ref([])
let jobList = ref([
	{ name: '班主任', id: 1 },
	{ name: '讲师', id: 2 },
	{ name: '学工主管', id: 3 },
	{ name: '教研主管', id: 4 },
	{ name: '咨询师', id: 5 },
])
let genderList = ref([
	{ name: '男', id: 1 },
	{ name: '女', id: 2 },
])
const addEmp = () => {
	editOrAdd.value = "add"
	dialogFormVisible.value = true
	request.get('/api/depts').then(res => {
		deptList.value = res.data
	})
}
const primaryAddEmp = () => {
	if (editOrAdd.value == "add") {
		delete form.value.id
		request.post("/api/emps", form.value).then(res => {
			ElMessage({
				message: res.msg,
				type: 'success',
			})
			getEmps()
			dialogFormVisible.value = false

		})
	} else if (editOrAdd.value == "edit") {
		request.put("/api/emps", form.value).then(res => {
			ElMessage({
				message: res.msg,
				type: 'success',
			})
			getEmps()
			dialogFormVisible.value = false

		})
	}
}
const closeDialog = (params) => {
	form.value = {
		id: '',
		username: '',
		name: '',
		gender: '',
		image: '',
		deptId: '',
		job: ''
	}
}

let currentPage4 = ref(1)//第几页
let pageSize4 = ref(5)//每页几条数据
let pageTotal = ref()


const handleSizeChange = (val) => {//切换每页显示条数
	getEmps(currentPage4.value, val, searchForm.value.name, searchForm.value.gender, searchForm.value.entryDateStart, searchForm.value.entryDateEnd)
	pageSize4.value = val
}
const handleCurrentChange = (val) => {//切换页码
	getEmps(val, pageSize4.value, searchForm.value.name, searchForm.value.gender, searchForm.value.entryDateStart, searchForm.value.entryDateEnd)
	currentPage4.value = val
}
let searchForm = ref({
	name: '',
	gender: '',
	entryDate: [],
	entryDateStart: '',
	entryDateEnd: '',
})

const shortcuts = [
	{
		text: '最近一周',
		value: () => {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
			return [start, end]
		},
	},
	{
		text: '最近一月',
		value: () => {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
			return [start, end]
		},
	},
	{
		text: '最近三月',
		value: () => {
			const end = new Date()
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
			return [start, end]
		},
	},
]
function padZeroToMonth(dateStr) {
	const [year, month, day] = dateStr.split('-').map(Number)
	const paddedMonth = month < 10 ? `0${month}` : month
	return `${year}-${paddedMonth}-${day}`
}

const onSearch = () => {
	searchForm.value.entryDateStart = searchForm.value.entryDate.length != 0 ? padZeroToMonth(searchForm.value.entryDate[0].toLocaleDateString().replace(/\//g, '-')) : ''
	searchForm.value.entryDateEnd = searchForm.value.entryDate.length != 0 ? padZeroToMonth(searchForm.value.entryDate[1].toLocaleDateString().replace(/\//g, '-')) : ''
	getEmps(currentPage4.value, pageSize4.value, searchForm.value.name, searchForm.value.gender, searchForm.value.entryDateStart, searchForm.value.entryDateEnd)
}
const onReset = (params) => {
	searchForm.value = {
		name: '',
		gender: '',
		entryDate: [],
		entryDateStart: '',
		entryDateEnd: '',
	}
	currentPage4.value = 1
	pageSize4.value = 5
	getEmps()
}


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file) => {
	console.log("resmove",file.url)
}

const handlePictureCardPreview = (file) => {
	dialogImageUrl.value = file.url
	dialogVisible.value = true
}

const handleDownload = (file) => {
	console.log(file.url)
}

const uploadSuccess = (file,upload) => {
	console.log('filessss :>> ', file,upload);
}

const uploadChange = async(file, fileLists) => {
	let formData = new FormData();
	formData.append('image', file.raw);
	try {
		const response = await request.post('/api/upload', formData, {
			headers: {
				'Content-Type': 'multipart/form-data'
			}
		});
		form.value.image=response.data
	} catch (error) {
		console.error('error :>> ', error);
	}
}
const bemo = (file,fileList) => {
	form.value.image=''
	console.log('object :>> ', file,fileList);
}
</script>

<template>
	<el-form :inline="true" :model="searchForm" class="demo-form-inline">
		<el-form-item label="姓名">
			<el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
		</el-form-item>
		<el-form-item label="性别">
			<el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
				<el-option v-for="(item, index) in genderList" :label="item.name" :value="item.id" />
			</el-select>
		</el-form-item>
		<el-form-item label="入职日期">
			<el-date-picker v-model="searchForm.entryDate" type="daterange" unlink-panels range-separator="至"
				start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" size="large" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="onSearch">搜索</el-button>
		</el-form-item>
		<el-form-item>
			<el-button type="warning" @click="onReset">重置</el-button>
		</el-form-item>
	</el-form>

	<el-button type="danger" size="large"><el-icon>
			<Minus />
		</el-icon>批量删除</el-button>
	<el-button type="primary" size="large" @click="addEmp"><el-icon>
			<Plus />
		</el-icon>新增</el-button>
	<el-table ref="multipleTableRef" :data="tableData" style="width: 100%" max-height="500px"
		@selection-change="handleSelectionChange">
		<el-table-column type="selection" />
		<el-table-column property="id" label="序号" sortable />
		<el-table-column property="name" label="姓名" />
		<el-table-column property="image" label="头像">
			<template #default="scope">
				<img width="100px" height="100px" :src="scope.row.image" />
			</template>

		</el-table-column>
		<el-table-column label="性别">

			<template #default="scope">{{ scope.row.gender == 1 ? '男' : '女' }}</template>
		</el-table-column>
		<el-table-column label="职位">

			<template #default="scope">
				{{ scope.row.job == 1 ? '班主任' : scope.row.job == 2 ? '讲师' : scope.row.job == 3 ? '学工主管' :
		scope.row.job == 4 ? '教研主管' : scope.row.job == 5 ? '咨询师' : '暂无职务' }}
			</template>
		</el-table-column>

		<el-table-column property="entrydate" label="入职日期" sortable />
		<el-table-column property="updateTime" label="最后操作时间" sortable />
		<!-- <template #default="scope">{{ scope.row.updateTime.replace(/\T/g, ' ') }}</template>
		</el-table-column> -->
		<el-table-column label="操作">

			<template #default="scope">
				<el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
				<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	<el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[5, 10, 20, 30]"
		background layout="total, sizes, prev, pager, next, jumper" :total="pageTotal" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />

	<el-dialog v-model="dialogFormVisible" :title="editOrAdd == 'edit' ? '修改学员信息' : editOrAdd == 'add' ? '新增学员' : ''"
		width="500" @close="closeDialog">
		<el-form :model="form">
			<el-form-item label="用户名" label-width="140px">
				<el-input v-model="form.username" autocomplete="off" />
			</el-form-item>
			<el-form-item label="姓名" label-width="140px">
				<el-input v-model="form.name" autocomplete="off" />
			</el-form-item>
			<el-form-item label="头像" label-width="140px">

				<el-upload action="#" accept="image/*" :limit="1" list-type="picture-card" :auto-upload="false" :on-success="uploadSuccess" :on-change="uploadChange" :on-remove="handleRemove" :before-remove="bemo">
					<el-icon>
						<Plus />
					</el-icon>

					<template #file="{ file }">
						<div>
							<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
							<span class="el-upload-list__item-actions">
								<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
									<el-icon><zoom-in /></el-icon>
								</span>
								<span v-if="!disabled" class="el-upload-list__item-delete"
									@click="handleDownload(file)">
									<el-icon>
										<Download />
									</el-icon>
								</span>
								<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
									<el-icon>
										<Delete />
									</el-icon>
								</span>
							</span>
						</div>
					</template>
				</el-upload>

				<el-dialog v-model="dialogVisible">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>
			<el-form-item label="性别" label-width="140px">
				<el-select v-model="form.gender" placeholder="请选择性别">
					<el-option v-for="(item, index) in genderList" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="职位" label-width="140px">
				<el-select v-model="form.job" placeholder="请选择职位">
					<el-option v-for="(item, index) in jobList" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="部门" label-width="140px">
				<el-select v-model="form.deptId" placeholder="请选择部门">
					<el-option v-for="(item, index) in deptList" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="primaryAddEmp">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.demo-form-inline .el-input {
	--el-input-width: 220px;
}

.demo-form-inline .el-select {
	--el-select-width: 220px;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>